package com.cat.chapter037;

/**
 * @author cat
 * @description https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-search-tree/
 * @create 2025/6/18 19:18
 * @since JDK17
 */

public class Solution02 {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (p.val > q.val) {
            int t = p.val;
            p.val = q.val;
            q.val = t;
        }
        while (root != null && root.val != p.val && root.val != q.val) {
            if (root.val > p.val && root.val < q.val) {
                break;
            }
            root = root.val < p.val ? root.right : root.left;
        }
        return root;
    }
}
